package org.duang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.bson.types.BSONTimestamp;
import org.duang.db.Connection;
import org.duang.http.base.HttpRes;
import org.duang.kit.HttpKit;
import org.duang.server.DuangServer;

import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.QueryOperators;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.taobao.api.ApiException;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
//        System.out.println( java.util.UUID.randomUUID() );
    	
//    	String path = "E:/info/V4运动视频/q";
//    	File filepath = new File(path);
//    	File[] files = filepath.listFiles();
//    	Map<String,String> map = new java.util.LinkedHashMap<String,String>();
//    	try{
//    	for(File file : files){
//    		InputStream in = new FileInputStream(file);
//    		String md5 = Digests.md5toString(in);
//    		System.out.println(file.getName() +"                            "+ md5);
//    		map.put(file.getName(), md5);
////    		Thread.sleep(1000L);
//    	}
//    	System.out.println(ToolsKit.toJsonString(map));
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
    	
//    	String str= "abc";
//    	System.out.println(str.split("\\?")[0]);
//    	BSONTimestamp ts = new BSONTimestamp(1, 1);
//    	Query query = new Query();
//    	query.gt("ts", ts);
//    	Order s = new Order();
//    	s.add("$natural", "1");
//    	query.order(s);
//    	System.out.println(query.getQueryObj());
//    	System.out.println(query.getDBOrder().toString());
//    	System.out.println(System.currentTimeMillis());
////    	1452129608232
////    	1452129158
//    	Date d = new Date(1452129608232L);
//    	System.out.println(d);
    	
//	String pwd1 = "syt.com";
//    	byte[] b = ToolsKit.buildEntryptSalt();
//    	String salt = ToolsKit.encodeHex(b);		//b6a32a22aab6a2ab
//    	String pwd = ToolsKit.buildEntryptPassword(pwd1, b);
//    	System.out.println(salt);
//    	System.out.println(pwd);
//    	b = ToolsKit.decodeHex(salt);
//    	pwd = ToolsKit.buildEntryptPassword(pwd1, b);
//    	
//    	System.out.println(pwd);
//    	try {
////			oplog();
//    		ObjectId oid = new ObjectId("5673c85d5abd9c051f61e387");
//    		System.out.println(oid.getDate());
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
    	
//    	String json = "{ \"query\": { \"multi_match\": { \"query\": \"猪肉\", \"type\": \"best_fields\", \"fields\": [ \"foodname\", \"typename\" ], \"tie_breaker\": 0.3 } }, \"from\":10, \"size\":20 }";
//    	HttpRes res = HttpKit.duang().url("http://192.168.0.39:9200/syt/FitNutrientV4/_search").body(json).post();
//    	System.out.println(ToolsKit.toJsonString(res.getResult()));
    	
//    	org.duang.db.mongo.Mongo mongoSyt = initMongo("syt");
//    	DB beauty = mongoSyt.getClient().getDB("beauty");
//    	System.out.println(mongoSyt.getDB().getName()+"                "+mongoSyt.getCollectionNames().size());
//    	System.out.println(mongoSyt.getDB().getName()+"                 "+beauty.getCollectionNames().size());
//    	closeDB();
    	
    	
    	
//    	putEsData();
//    	try {
//			openapi();
//		} catch (ApiException e) {
//			e.printStackTrace();
//		}
    }
    
    
    public static void putEsData() {
    	org.duang.db.mongo.Mongo mongo = initMongo("syt");
    	MongoCollection<Document> docs = mongo.getCollection("syt", "FitNutrientV4");
    	FindIterable<Document> iterable = docs.find().limit(100);
    	StringBuilder url = new StringBuilder("http://42.96.139.238:9200/syt/FitNutrientV4/");
    	StringBuilder id = new StringBuilder();
    	int i=0;
    	for(Iterator<Document> it = iterable.iterator(); it.hasNext();){
    		Document doc = it.next();
    		id.append(doc.get("_id").toString());
    		url.append(id);
    		doc.remove("_id");
    		HttpRes res = HttpKit.duang().url(url.toString()).body(doc.toJson()).post();
    		System.out.println((++i) + "            "+id +"                    "+res.getResult());
    		id.delete(0, id.length());
    		url.delete(url.length()-24, url.length());
    	}
    	closeDB();
    }
    
    public static org.duang.db.mongo.Mongo initMongo(String dbname) {
    	Map<String, String> optionMap = new HashMap<String,String>();
    	optionMap.put(Connection.REPLICASET_FIELD, "115.29.128.156:38250,115.29.128.173:38250");
		optionMap.put(Connection.DATABASE_FIELD,  dbname);
		try {
			org.duang.db.mongo.Mongo mongo = org.duang.db.mongo.Mongo.getInstance();
			mongo.connect(optionMap);
			return mongo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
    private static void closeDB() {
    	try{
    		org.duang.db.mongo.Mongo.getInstance().close();
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }
    

public static void oplog() throws Exception {
    Mongo mongo = new Mongo("115.29.128.156", 38257);
//    Mongo mongos = new Mongo("139.129.192.54", 38101);
    DB db = mongo.getDB("local");
//    DB syt = mongos.getDB("syt");
    DBCollection collection = db.getCollection("oplog.rs");
    if (collection != null) {
        BSONTimestamp ts = new BSONTimestamp(1452174603, 23);// { "$ts" : 1450655619 , "$inc" : 234}
        final BasicDBObject query = new BasicDBObject();
        query.append("ts", new BasicDBObject(QueryOperators.GT, ts));
        DBCursor cursor = collection.find(query).sort(new BasicDBObject("$natural", 1));
        System.out.println("cursor.getBatchSize(): " + cursor.getBatchSize());
        cursor.setOptions(Bytes.QUERYOPTION_TAILABLE);
        cursor.setOptions(Bytes.QUERYOPTION_OPLOGREPLAY);
        cursor.setOptions(Bytes.QUERYOPTION_AWAITDATA);
        while (cursor != null && cursor.hasNext()) {
            DBObject obj = cursor.tryNext();//.next();
//            String ns = obj.get("ns").toString();
//            String tableName = ns.substring(ns.indexOf(".")+1, ns.length());
//            DBCollection coll = syt.getCollection(tableName);
            int lastTime = ((BSONTimestamp)obj.get("ts")).getTime();
        	int lastIncrement = ((BSONTimestamp)obj.get("ts")).getInc();
            System.out.println(lastTime+"               "+lastIncrement+"               "+obj.get("ns")+"                    "+obj.get("op")+"             "+ ((DBObject)obj.get("o")).get("_id"));
//            if(obj.get("op").equals("i")){
	           // coll.insert((DBObject)obj.get("o"));
//	            System.out.println(((DBObject)obj.get("o")).get("_id").toString()+"                           "+ obj.get("ns") +"                           "+ obj.get("op"));
//            }
          }
    }
}



public static void openapi() throws ApiException {
	/*
	TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23274057", "c8b976c64baaa4b01dfb213b8aac01d3");
	
	OpenApiRequest request = new OpenApiRequest();
	OpenApiResponse response = client.execute(request);
//	TimeGetRequest request = new TimeGetRequest();
//	TimeGetResponse response = client.execute(request);
	System.out.println("############: " + JSON.toJSONString(response));
	if (response.isSuccess()) {
	    System.out.println(response.getBody());
	}
//	TaobaoClient client = new DefaultTaobaoClient("taobao.user.seller.get", "23274057", "c8b976c64baaa4b01dfb213b8aac01d3");
//	client.execute(arg0)
//	UserSellerGetRequest req = new UserSellerGetRequest();
//	req.setFields("nick,sex");
//	UserSellerGetResponse rsp = client.execute(req, sessionKey);
//	System.out.println(rsp.getBody());
 */
	
	
	List<String> list = new ArrayList<String>();
	for(int i=1; i<=20; i++){
		list.add(i+"");
	}
	System.out.println(list);
	list.add(1, "21");
	System.out.println(list);
}

}
